import re
import os
import shutil
import urllib
#from django.utils.html import escape
from django.template.defaultfilters import slugify
from models import *
#from mutagen.mp3 import *
from mutagen.easyid3 import *
import settings

new_artists = 0
new_albums = 0
new_tracks = 0

def get_song_data(filename):
    metadata = mutagen.mp3.Open(filename)
    return metadata
    
def recursive_folder_import(base_folder, recursing=False):
    try:
        filelist = os.listdir(base_folder)
    except:
        print 'can\'t list %s' % base_folder
        return
    print '**working in folder %s**' % base_folder
    subfolders = [folder for folder in filelist if os.path.isdir(os.path.join(base_folder,folder))]
    files = [os.path.join(base_folder, f) for f in filelist if not f in subfolders]
    #print 'found these files: %s' % files
    import_files(files)
    for folder in subfolders:
        if not folder.startswith('.'): # svn or other hidden folder
            recursive_folder_import(os.path.join(base_folder,folder), recursing=True)
    if not recursing:
        print 'created %s new artists, %s new albums and %s new tracks' % (new_artists, new_albums, new_tracks)
        
def import_files(songs):
    global new_artists
    global new_albums
    global new_tracks
    for song_file in songs:
        try:
            song = EasyID3(song_file)
        except:
            print '%s is not a music file or has no tags' % song_file
            continue
        
        #print song['artist'], song['album'], song['tracknumber'], song['title'], 
        try:    
            artist, new_artist_flag = Artist.objects.get_or_create(title=str(song['artist'][0]))
            if new_artist_flag:
                new_artists += 1
            album, new_album_flag = Album.objects.get_or_create(title=str(song['album'][0]), artist=artist)
            if new_album_flag:
                new_albums += 1
        except:
            from django.db import connection
            print connection.queries
            raise
            

        if album.artist:
            assert album.artist.id == artist.id
        else:
            album.artist = artist
            album.save()
        
        trackno = song['tracknumber'][0].split('/')[0]
        artist_dir = slugify(artist.title)
        album_dir = slugify(album.title)
        try:
            os.makedirs(os.path.join(settings.MP3_DIRECTORY, artist_dir, album_dir))
        except:
            pass  
        track, new_track_flag = Track.objects.get_or_create(title=song['title'][0], album=album, number=trackno)
        escaped_title = slugify(track.title)
        destination_file = '%s/%s/%s/%s.mp3' % (settings.MP3_DIRECTORY,
            artist_dir, album_dir, escaped_title)
        try:
            shutil.copyfile(song.filename, os.path.join(*destination_file.split('/')))
        except shutil.Error:
            pass # probably already moved file; don't re-add
        track.mp3=destination_file
        if new_track_flag:
            new_tracks += 1
        track.album = album
        track.save()
    
    #print 'created %s new artists, %s new albums and %s new tracks' % (new_artists, new_albums, new_tracks)
